package com.example.filter;

import com.alibaba.fastjson.JSON;
import com.example.common.BaseContext;
import com.example.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "/loginCheckFilter" , urlPatterns = "/*")
@Slf4j
//@Component
public class LoginCheckFilter implements Filter {
    //路径匹配器
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强制转换成HttpServletRequest
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取请求
        String uri = request.getRequestURI();
        //记录日志
        log.info("拦截到的请求路径：" + uri);

        //判断本次请求是否需要处理，返回true表示不需要处理，放行即可
        if(check(uri)){
            log.info("不需要处理，放行路径：" + uri);
            filterChain.doFilter(request , response);
            return;
        }

        //判断是否登录了
        if(request.getSession().getAttribute("user") != null){
            //登录了，放行路径
            log.info("已登录，用户id为：" + request.getSession().getAttribute("user"));

            Long userId = (Long)request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request , response);
            return;
        }

        log.info("用户未登录！");
        response.getWriter().write(JSON.toJSONString("not login"));
        return;
    }
    //判断请求路径是否需要拦截
    public boolean check(String uri){
        //不需要拦截的路径用数组存起来
        String[] urls = new String[]{
                "/user/login"
        };
        //进行判断
        for(String url : urls){
            if(PATH_MATCHER.match(url , uri)){
                return true;
            }
        }
        return false;
    }
}
